<template>
    <el-container class="container">
        <el-aside class="aside">
            <el-row class="toolbar">
                <div>
                    <el-button type="primary" @click="addDict" :disabled="dictAddButtonDisabled">新增</el-button>
                    <el-button type="danger" plain :disabled="dictDeleteButtonDisabled"
                        @click="deleteSelectedDicts">删除</el-button>
                </div>
                <el-button-group>
                    <el-button type="default" @click="refreshDict">刷新</el-button>
                </el-button-group>
            </el-row>
            <el-table class="table" :data="dictData" v-loading="dictLoading"
                @selection-change="handleDictSelectionChange" @row-click="handleDictRowClick"
                :row-class-name="dictTableRowClassName" row-key="id"
                :default-sort="{ prop: 'label', order: 'ascending' }">
                <el-table-column type="selection" header-align="center" align="center" />
                <el-table-column prop="id" label="id" align="center" v-if="false" />
                <el-table-column prop="name" label="字典" align="center" />
                <el-table-column fixed="right" label="操作" width="120">
                    <template #default="scope">
                        <el-button link type="primary" size="small" @click="editDict(scope.row)">
                            编辑
                        </el-button>
                        <el-button link type="primary" size="small" @click="deleteDict(scope.row)">
                            删除
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>
        </el-aside>
        <el-main class="main">
            <el-row class="toolbar">
                <div>
                    <el-button type="primary" @click="addDictChildren"
                        :disabled="dictChildrenAddButtonDisabled">新增</el-button>
                    <el-button type="danger" plain :disabled="dictChildrenDeleteButtonDisabled"
                        @click="deleteSelectedDictChildren">删除</el-button>
                </div>
                <el-button-group>
                    <el-button type="default" :disabled="dictChildrenRefreshDisabled"
                        @click="refreshDictChildren">刷新</el-button>
                </el-button-group>
            </el-row>
            <el-table class="table" :data="dictChildrenData" stripe v-loading="dictChildrenLoading"
                @selection-change="handleDictChildrenSelectionChange" row-key="id"
                :default-sort="{ prop: 'value', order: 'ascending' }">
                <el-table-column type="selection" header-align="center" align="center" />
                <el-table-column prop="id" label="id" width="80" align="center" v-if="false" />
                <el-table-column prop="label" label="键" align="center" width="150" />
                <el-table-column prop="value" label="值" align="center" />
                <el-table-column fixed="right" label="操作" width="120">
                    <template #default="scope">
                        <el-button link type="primary" size="small" @click="editDictChildren(scope.row)">
                            编辑
                        </el-button>
                        <el-button link type="primary" size="small" @click="deleteDictChildren(scope.row)">
                            删除
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>
        </el-main>
    </el-container>
    <el-dialog v-model="dictDialogVisible" :title="dictDialogTitle" width="30%" draggable :close-on-click-modal="false">
        <el-form :model="dictForm" ref="dictFormRef" :rules="dictRules">
            <el-form-item label="字典名称" prop="name" required>
                <el-input v-model="dictForm.name" placeholder="请填写字典名称"></el-input>
            </el-form-item>
        </el-form>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="dictDialogVisible = false">取消</el-button>
                <el-button type="primary" @click="submitDictForm" :loading="dictSubmitLoading">
                    {{ dictSubmitText }}
                </el-button>
            </div>
        </template>
    </el-dialog>
    <el-dialog v-model="dictChildrenDialogVisible" :title="dictChildrenDialogTitle" width="30%" draggable
        :close-on-click-modal="false">
        <el-form :model="dictChildrenForm" ref="dictChildrenFormRef" :rules="dictChildrenRules">
            <el-row :gutter="15">
                <el-col :span="12">
                    <el-form-item label="键" prop="label" required>
                        <el-input v-model="dictChildrenForm.label" placeholder="请填写键"></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="值" prop="value" required>
                        <el-input-number v-model="dictChildrenForm.value" placeholder="请填写值"
                            :controls="false"></el-input-number>
                    </el-form-item>
                </el-col>
            </el-row>
        </el-form>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="dictChildrenDialogVisible = false">取消</el-button>
                <el-button type="primary" @click="submitDictChildrenForm" :loading="dictChildrenSubmitLoading">
                    {{ dictChildrenSubmitText }}
                </el-button>
            </div>
        </template>
    </el-dialog>
</template>
<script setup>
import { ref, onMounted, watch, nextTick } from "vue";
import { useCookies } from "vue3-cookies";
const { cookies } = useCookies();
import useStore from "@/store/index";
import { errorNotify } from '@/utils/Misc';

const store = useStore();
import dictAPI from "@/api/dict/list";
import dictChildrenAPI from "@/api/dict/item";
import { ElMessage, ElMessageBox, ElLoading } from "element-plus";


const dictData = ref([]);
const dictLoading = ref(true);
const dictAddButtonDisabled = ref(false);
const dictDeleteButtonDisabled = ref(true);
const selectedDicts = ref([]);
const dictIDs = ref("");
const dictDialogVisible = ref(false);
const dictDialogTitle = ref("");
const dictSubmitLoading = ref(false);
const dictSubmitText = ref("提交");
const dictFormRef = ref(null);
const dictRules = ref({
    name: [
        { required: true, message: "字典数据名称不能为空", trigger: "blur" },
    ],
});
const dictForm = ref({
    id: "",
    name: "",
});


const dictChildrenData = ref([]);
const dictChildrenLoading = ref(false);
const dictChildrenAddButtonDisabled = ref(true);
const dictChildrenDeleteButtonDisabled = ref(true);
const dictChildrenRefreshDisabled = ref(true);
const selectedDictChildren = ref([]);
const dictChildrenIDs = ref("");
const dictChildrenDialogVisible = ref(false);
const dictChildrenDialogTitle = ref("");
const dictChildrenSubmitLoading = ref(false);
const dictChildrenSubmitText = ref("提交");
const dictChildrenFormRef = ref(null);
const dictChildrenRules = ref({
    label: [
        { required: true, message: "键不能为空", trigger: "blur" },
    ],
    value: [
        { required: true, message: "值不能为空", trigger: "blur" },
    ]
});
const dictChildrenForm = ref({
    id: "",
    dictId: "",
    label: "",
    value: "",
});

const currentDictId = ref("");


onMounted(() => {
    const token = cookies.get("token");
    if (!token) {
        window.location.href = "/login?path=ZiDian";
        return;
    }
    loadDict();
});



const loadDict = () => {
    dictLoading.value = true;
    dictAPI.list().then((res) => {
        dictData.value = res.data.page.list;
        dictLoading.value = false;
    }).catch(error => {
        errorNotify("ZiDian.vue", "loadDict", error);
    });
};


const refreshDict = () => {
    loadDict();
};


const handleDictSelectionChange = (selection) => {
    selectedDicts.value = selection;
    dictDeleteButtonDisabled.value = selection.length === 0;
    dictIDs.value = selection.map(item => item.value).join(",");
};

const handleDictRowClick = (row) => {
    loadDictChildren(row.id)
    currentDictId.value = row.id;
    dictChildrenAddButtonDisabled.value = false;
    dictChildrenRefreshDisabled.value = false;
};

const dictTableRowClassName = ({ row }) => {
    return row.id === currentDictId.value ? 'dict-row-current' : '';
};
const addDict = () => {
    resetDictForm();
    dictDialogVisible.value = true;
    dictDialogTitle.value = "新建字典";
    dictSubmitText.value = "提交";
};


const editDict = (row) => {
    dictForm.value.id = row.id;
    dictForm.value.name = row.name;
    dictDialogVisible.value = true;
    dictDialogTitle.value = "编辑字典";
    dictSubmitText.value = "更新";
};


const deleteDict = (row) => {
    ElMessageBox.confirm("确定删除该字典吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
    }).then(() => {
        const deleteLoadingMessage = ElMessage.info({
            message: "删除中...",
            duration: 0,
            showClose: false
        });
        dictAPI.delete(row.id).then(() => {
            ElMessage.success("删除成功");
            loadDict();
        }).catch(() => {
            ElMessage.error("删除失败");
        }).finally(() => {
            deleteLoadingMessage.close();
        });
    }).catch(() => { });
};


const deleteSelectedDicts = () => {
    if (selectedDicts.value.length === 0) return;
    ElMessageBox.confirm(`确定删除选中的${selectedDicts.value.length}个字典吗？`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
    }).then(() => {
        const deleteLoadingMessage = ElMessage.info({
            message: "删除中...",
            duration: 0,
            showClose: false
        });
        dictAPI.delete(dictIDs.value).then(() => {
            ElMessage.success("删除成功");
            loadDict();
        }).catch(() => {
            ElMessage.error("删除失败");
        }).finally(() => {
            deleteLoadingMessage.close();
        });
    }).catch(() => { });
};


const submitDictForm = () => {
    dictSubmitLoading.value = true;
    dictFormRef.value.validate((valid) => {
        if (valid) {
            dictAPI.save(dictForm.value).then(() => {
                if (dictDialogTitle.value === "编辑字典") {
                    ElMessage.success("更新字典成功");
                } else {
                    ElMessage.success("新建字典成功");
                }
                dictDialogVisible.value = false;
                loadDict();
            }).catch((error) => {
                errorNotify("ZiDian.vue", "submitDictForm", error);
            }).finally(() => {
                dictSubmitLoading.value = false;
            });
        } else {
            dictSubmitLoading.value = false;
        }
    });
};


const resetDictForm = () => {
    dictForm.value = {
        id: "",
        name: "",
    };
    if (dictFormRef.value) {
        dictFormRef.value.resetFields();
    }
};



const loadDictChildren = (dictId) => {
    dictChildrenLoading.value = true;
    dictChildrenAPI.list(dictId).then((res) => {
        dictChildrenData.value = res.data.page.list
        dictChildrenLoading.value = false;
    }).catch(error => {
        errorNotify("ZiDian.vue", "loadDictChildren", error);
    });
};


const refreshDictChildren = () => {
    loadDictChildren(currentDictId.value);
};


const handleDictChildrenSelectionChange = (selection) => {
    selectedDictChildren.value = selection;
    dictChildrenDeleteButtonDisabled.value = selection.length === 0;
    dictChildrenIDs.value = selection.map(item => item.id).join(",");
};


const addDictChildren = () => {
    resetDictChildrenForm();
    dictChildrenForm.value.dictId = currentDictId.value;
    dictChildrenDialogVisible.value = true;
    dictChildrenDialogTitle.value = "新建字典数据";
    dictChildrenSubmitText.value = "提交";
};


const editDictChildren = (row) => {
    dictChildrenForm.value.label = row.label;
    dictChildrenForm.value.value = row.value;
    dictChildrenForm.value.id = row.id;
    dictChildrenDialogVisible.value = true;
    dictChildrenDialogTitle.value = "编辑字典数据";
    dictChildrenSubmitText.value = "更新";
};


const deleteDictChildren = (row) => {
    ElMessageBox.confirm("确定要删除吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
    }).then(() => {
        const deleteLoadingMessage = ElMessage.info({
            message: "删除中...",
            duration: 0,
            showClose: false
        });
        dictChildrenAPI.delete(row.id).then(() => {
            ElMessage.success("删除成功");
            loadDictChildren(currentDictId.value);
        }).catch(() => {
            ElMessage.error("删除失败");
        }).finally(() => {
            deleteLoadingMessage.close();
        });
    }).catch((error) => {
        errorNotify("ZiDian.vue", "deleteDictChildren", error);
    });
};


const deleteSelectedDictChildren = () => {
    if (selectedDictChildren.value.length === 0) return;
    ElMessageBox.confirm(`确定删除选中的${selectedDictChildren.value.length}个字典项吗？`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
    }).then(() => {
        const deleteLoadingMessage = ElMessage.info({
            message: "删除中...",
            duration: 0,
            showClose: false
        });
        dictChildrenAPI.delete(dictChildrenIDs.value).then(() => {
            ElMessage.success("删除成功");
            loadDictChildren(currentDictId.value);
        }).catch(() => {
            ElMessage.error("删除失败");
        }).finally(() => {
            deleteLoadingMessage.close();
        });
    }).catch(() => { });
};


const submitDictChildrenForm = () => {
    dictChildrenSubmitLoading.value = true;
    dictChildrenFormRef.value.validate((valid) => {
        if (valid) {
            dictChildrenAPI.save(dictChildrenForm.value).then(() => {
                if (dictChildrenDialogTitle.value === "编辑字典数据") {
                    ElMessage.success("更新字典数据成功");
                } else {
                    ElMessage.success("新建字典数据成功");
                }
                dictChildrenDialogVisible.value = false;
                loadDictChildren(currentDictId.value);
            }).catch((error) => {
                errorNotify("ZiDian.vue", "submitDictChildrenForm", error);
            }).finally(() => {
                dictChildrenSubmitLoading.value = false;
            });
        } else {
            dictChildrenSubmitLoading.value = false;
        }
    });
};


const resetDictChildrenForm = () => {
    dictChildrenForm.value = {
        id: "",
        dictId: "",
        label: "",
        value: "",
    };
    if (dictChildrenFormRef.value) {
        dictChildrenFormRef.value.resetFields();
    }
};
</script>
<style scoped>
.container {
    height: calc(100vh - 52px);
}

.aside {
    width: 30%;
    padding: 1%;
    border: 1px solid #ccc;
}

.main {
    height: calc(100vh - 52px);
    border: 1px solid #ccc;
}

.toolbar {
    display: flex;
    justify-content: space-between;
    margin-bottom: 1%;
}

.table {
    margin-bottom: 2%;
}

.form-item {
    margin-right: 1%;
}

:deep(.el-table tbody tr:hover) {
    cursor: pointer;
}

:deep(.dict-row-current) {
    background-color: var(--el-color-primary-light-9) !important;
    color: var(--el-color-primary) !important;
    font-weight: 600;
}
</style>
